﻿window.ArthurGraus = window.ArthurGraus || {};

var Action;

$(document).ready(function () {
    Action = new ArthurGraus.SharePointFileExplorerCustomAction();
    Action.initialize();
});

ArthurGraus.SharePointFileExplorerCustomAction = function () {

    var mainself = this;
    mainself.camlQuery = new SP.CamlQuery.createAllItemsQuery();
    mainself.hostWebUrl = "";
    mainself.appWebContext = null;
    mainself.hostWebContext = null;
    mainself.hostWeb = null;
    mainself.list = null;
    mainself.listItems = new Array();
    mainself.listId = null;
    mainself.itemId = null;
    mainself.itemCollection = null;
    mainself.filesToCopy = new Array();
    mainself.foldersToCopy = new Array();
    mainself.fileItems = new Array();
    mainself.folderItems = new Array();
    mainself.itemIdArray = new Array();
    mainself.currentLibraryItems = new Array();
    mainself.subfolderStrings = new Array();
    var waitDialog = null;

    mainself.wait = function () {
        //waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15);
    }
    mainself.cancelWait = function () {
        //waitDialog.close();
    }
    mainself.initialize = function () {
        mainself.wait();
        //alert(document.URL);
        var listIdArray = getQueryStringParameter("List");
        if (listIdArray.length > 0)
            mainself.listId = listIdArray[0];
        else
            mainself.closeDialog();
        mainself.itemIdArray = getQueryStringParameter("Selected");
        if (mainself.itemIdArray[0] == "null")
            mainself.closeDialog();
        mainself.hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
        mainself.appWebContext = new SP.ClientContext.get_current();
        mainself.hostWebContext = new SP.AppContextSite(mainself.appWebContext, mainself.hostWebUrl);
        mainself.hostWeb = mainself.hostWebContext.get_web();
        mainself.list = mainself.hostWeb.get_lists().getById(mainself.listId);
        mainself.appWebContext.load(mainself.list);
        mainself.appWebContext.executeQueryAsync(mainself.getListItem, mainself.onError);
    }
    mainself.getListItem = function () {
        for (var num in mainself.itemIdArray) {
            mainself.listItems.push(mainself.list.getItemById(mainself.itemIdArray[num]));
            mainself.appWebContext.load(mainself.listItems[mainself.listItems.length-1]);   
        }
        mainself.appWebContext.executeQueryAsync(mainself.CopyItem, mainself.onError);

    }
    mainself.CopyItem = function () {
        for (var num in mainself.listItems) {
            if (mainself.listItems[num].get_fileSystemObjectType() == 0) {
                mainself.filesToCopy.push(mainself.listItems[num].get_file());
                mainself.fileItems.push(mainself.listItems[num]);
                mainself.appWebContext.load(mainself.filesToCopy[mainself.filesToCopy.length-1]);
            }
            else if (mainself.listItems[num].get_fileSystemObjectType() == 1) {
                mainself.foldersToCopy.push(mainself.listItems[num].get_folder());
                mainself.folderItems.push(mainself.listItems[num]);
                mainself.appWebContext.load(mainself.foldersToCopy[mainself.foldersToCopy.length - 1]);
            }

        }
        mainself.appWebContext.executeQueryAsync(mainself.CopyFile, mainself.onError);
    }
    mainself.CopyFile = function () {
        if (mainself.filesToCopy.length > 0) {
            for (var num in mainself.filesToCopy) {
                var NewName = mainself.NewFileName(mainself.filesToCopy[num].get_name());
                var _destinationlibUrl = mainself.fileItems[num].get_fieldValues().FileDirRef + '/' + NewName;
                mainself.filesToCopy[num].copyTo(_destinationlibUrl, true);
            }
            mainself.appWebContext.executeQueryAsync(mainself.checkFolderItem, mainself.onError);
        }
        else {
            mainself.itemCollection = mainself.list.getItems(mainself.camlQuery);
            mainself.appWebContext.load(mainself.itemCollection);
            mainself.appWebContext.executeQueryAsync(mainself.onLoadLibraryFiles, mainself.onError);
        }
    }
    mainself.checkFolderItem = function () {
        var folderCount = 0;
        for (var num in mainself.listItems) {
            if (mainself.listItems[num].get_fileSystemObjectType() == 1) {
                folderCount++;
                mainself.itemCollection = mainself.list.getItems(mainself.camlQuery);
                mainself.appWebContext.load(mainself.itemCollection);
                mainself.appWebContext.executeQueryAsync(mainself.onLoadLibraryFiles, mainself.onError);
            }

        }
        if (folderCount == 0) {
            mainself.cancelWait();
            mainself.closeDialog();
        }
    }

    mainself.onLoadLibraryFiles = function () {
        var itemEnumerator = mainself.itemCollection.getEnumerator();
        while (itemEnumerator.moveNext()) {
            mainself.currentLibraryItems.push(itemEnumerator.get_current());
        }
        for (var num in mainself.currentLibraryItems) {
            if (mainself.currentLibraryItems[num].get_fileSystemObjectType() == 0) {
                mainself.appWebContext.load(mainself.currentLibraryItems[num], "File");
            }
        }
        mainself.appWebContext.load(mainself.foldersToCopy[0], "ParentFolder");
        mainself.appWebContext.executeQueryAsync(mainself.onLoadLibrary, mainself.onError);

    }

    mainself.onLoadLibrary = function () {
        var subfoldersAl = new Array();
        for (var number in mainself.foldersToCopy) {
            var NewSubfolderArray = new Array();
            NewSubfolderArray.push(mainself.foldersToCopy[number].get_name());
            var FileRef = mainself.foldersToCopy[number].get_serverRelativeUrl();
            FileRef = FileRef.substring(0, FileRef.length - mainself.foldersToCopy[number].get_name().length);
            FileRef += mainself.foldersToCopy[number].get_name();
            mainself.onFolderCopy(FileRef, NewSubfolderArray);
        }
        for (var num in mainself.subfolderStrings) {
            var subArray = new Array();
            for (var count in mainself.subfolderStrings[num]) {
                subArray.push(mainself.subfolderStrings[num][count]);
            }
            subfoldersAl.push(subArray);
        }
        for (var num in mainself.subfolderStrings) {
            mainself.subfolderStrings[num][0] = mainself.subfolderStrings[num][0] + " - Copy";
        }
        var Destination = mainself.folderItems[0].get_fieldValues().FileDirRef;

        for (var number in mainself.subfolderStrings) {
            var makeSubfolder = mainself.foldersToCopy[0].get_parentFolder();
            for (var num in mainself.subfolderStrings[number]) {
                makeSubfolder = makeSubfolder.get_folders().add(mainself.subfolderStrings[number][num]);

            }
            mainself.appWebContext.executeQueryAsync();
        }
        for (var number in mainself.subfolderStrings) {
            var CurrentDestination = "";
            var CurrentOldDestination = "";
            CurrentOldDestination += Destination;
            CurrentDestination += Destination;
            for (var num in mainself.subfolderStrings[number]) {
                CurrentDestination += "/" + mainself.subfolderStrings[number][num];
                CurrentOldDestination += "/" + subfoldersAl[number][num];
                for (var num in mainself.currentLibraryItems) {
                    var CurrentFileRef = "";
                    CurrentFileRef += CurrentOldDestination + "/" + mainself.currentLibraryItems[num].get_fieldValues().FileLeafRef;
                    if (mainself.currentLibraryItems[num].get_fieldValues().FileRef == CurrentFileRef && mainself.currentLibraryItems[num].get_fileSystemObjectType() == 0) {
                        mainself.onFileCopyByUrl(CurrentDestination, mainself.currentLibraryItems[num].get_file());
                    }
                }
            }

        }
        mainself.appWebContext.executeQueryAsync(mainself.closeDialog, mainself.onError);
    }

    mainself.onFileCopyByUrl = function (Destination, File) {
        var _destinationlibUrl = Destination + '/' + File.get_name();
        File.copyTo(_destinationlibUrl, true);
    }


    mainself.onFolderCopy = function (FileDirRef, Folder) {
        var NewSubfolderArray = new Array();
        var countCheck = 0;
        for (var num in Folder) {
            NewSubfolderArray.push(Folder[num]);
        }
        for (var num in mainself.currentLibraryItems) {
            if (mainself.currentLibraryItems[num].get_fieldValues().FileDirRef == FileDirRef && mainself.currentLibraryItems[num].get_fileSystemObjectType() == 1) {
                NewSubfolderArray.push(mainself.currentLibraryItems[num].get_fieldValues().FileLeafRef);
                var FileRef = mainself.currentLibraryItems[num].get_fieldValues().FileRef;
                mainself.onFolderCopy(FileRef, NewSubfolderArray);
                NewSubfolderArray.pop();
                countCheck++;
            }
        }
        if (countCheck == 0)
            mainself.subfolderStrings.push(NewSubfolderArray);

    }

    mainself.closeDialog = function () {
        var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
        target.postMessage('CloseCustomActionDialogRefresh', '*');
    }
    mainself.NewFileName = function (Name) {
        var array = Name.split('.');
        var newFileName = array[0] + " - Copy" + "." + array[1];
        return newFileName;
           
    }
    mainself.onError = function (sender, args) {
        alert('Request failed. ' + args.get_message() +
        '\n' + args.get_stackTrace());
        mainself.closeDialog();
    }


};
function getQueryStringParameter(paramToRetrieve) {
    var params =
        document.URL.split("?")[1].split("&");
    var multipleParam = new Array();
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == paramToRetrieve) {
            var paramToSplit = singleParam[1].split(",");
            for (var num in paramToSplit) {
                multipleParam.push(paramToSplit[num]);
            }
        }
    }
    if (multipleParam.length > 0)
        return multipleParam;
    else
        return null;
}
